package cs.android.view;

import static cs.java.lang.Lang.is;
import static cs.java.lang.Lang.no;

import android.app.Dialog;
import cs.android.ActivityView;
import cs.android.R;
import cs.android.lang.ServerRequest;
import cs.android.viewbase.ActivityViewBase;
import cs.java.event.Task;

public class ProgressDialogView extends ActivityViewBase {

	private Dialog progressDialog;
	private ServerRequest request;

	public ProgressDialogView(ActivityView parent) {
		super(parent);
	}

	@Override protected void onPause() {
		super.onPause();
		hideDialog();
	}

	@Override protected void onResume() {
		super.onResume();
		update();
	}

	private void hideDialog() {
		if (is(progressDialog)) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	private void onRequestDone() {
		request = null;
		hideDialog();
	}

	private void showProgress() {
		if (is(progressDialog)) return;
		progressDialog = new Dialog(getActivity(), R.style.LoadingDialogTheme);
		progressDialog.setCancelable(false);
		progressDialog.setContentView(R.layout.load_indicator_dialog);
		progressDialog.show();
	}

	private void update() {
		if (no(request)) hideDialog();
		else if (request.isDone()) onRequestDone();
		else {
			showProgress();
			new Task(this, request.getOnDone(), "on_done") {
				public void run() {
					if (isResumed()) onRequestDone();
				}
			};
		}
	}

	public void setRequest(ServerRequest request) {
		this.request = request;
		update();
	}

}
